package com.by.springboottwodatabases.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.by.springboottwodatabases.controller.request.TestRequestBean;
import com.by.springboottwodatabases.controller.request.TwoRequestBean;
import com.by.springboottwodatabases.domain.two.DTestTwo;
import com.by.springboottwodatabases.domain.two.DTwo;
import com.by.springboottwodatabases.domain.two.repository.DTestTwoRepository;
import com.by.springboottwodatabases.domain.two.repository.DTwoRepository;
import com.by.springboottwodatabases.service.TwoService;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class TwoServiceImpl implements TwoService {

    private final DTwoRepository twoRepository;
    private final DTestTwoRepository testRepository;

    public TwoServiceImpl(DTwoRepository twoRepository, DTestTwoRepository testRepository) {
        this.twoRepository = twoRepository;
        this.testRepository = testRepository;
    }


    @Override
    public DTwo createTwo(TwoRequestBean bean) {
        DTwo two = new DTwo();
        BeanUtil.copyProperties(bean, two);
        return twoRepository.save(two);
    }

    @Override
    public DTwo findById(Long id) {
        Optional<DTwo> two = twoRepository.findById(id);
        return two.orElse(null);
    }

    @Override
    public DTwo updateTwo(Long id, TwoRequestBean bean) {
        DTwo two = findById(id);
        BeanUtil.copyProperties(bean, two, true);
        return twoRepository.save(two);
    }

    @Override
    public void deleteTwo(Long id) {
        twoRepository.deleteById(id);
    }

    @Override
    public DTestTwo createTest(TestRequestBean bean) {
        DTestTwo test = new DTestTwo();
        BeanUtil.copyProperties(bean, test, true);
        return testRepository.save(test);
    }

    @Override
    public DTestTwo findTestById(Long id) {
        Optional<DTestTwo> test = testRepository.findById(id);
        return test.orElse(null);
    }

    @Override
    public DTestTwo updateTest(Long id, TestRequestBean bean) {
        DTestTwo test = findTestById(id);
        BeanUtil.copyProperties(bean, test, true);
        return testRepository.save(test);
    }

    @Override
    public void deleteTest(Long id) {
        testRepository.deleteById(id);
    }
}
